<template>
  <div class="invoice-template">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>发票模板管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加模板
      </el-button>
    </div>

    <!-- 模板列表 -->
    <el-card class="template-list">
      <el-table
        v-loading="loading"
        :data="templateList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="type" label="发票类型" width="150">
          <template #default="{ row }">
            <el-tag :type="row.type === 'special' ? 'success' : 'info'">
              {{ row.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="发票抬头" min-width="200" show-overflow-tooltip />
        <el-table-column prop="taxNumber" label="税号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="bankName" label="开户银行" min-width="150" show-overflow-tooltip />
        <el-table-column prop="bankAccount" label="银行账号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="address" label="注册地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="phone" label="注册电话" width="120" />
        <el-table-column prop="isDefault" label="默认模板" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isDefault ? 'success' : 'info'">
              {{ row.isDefault ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              v-if="!row.isDefault"
              type="success" 
              link 
              @click="handleSetDefault(row)"
            >
              设为默认
            </el-button>
            <el-button 
              v-if="!row.isDefault"
              type="danger" 
              link 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加模板' : '编辑模板'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="发票类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="special">增值税专用发票</el-radio>
            <el-radio label="normal">增值税普通发票</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发票抬头" prop="title">
          <el-input v-model="form.title" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="税号" prop="taxNumber">
          <el-input v-model="form.taxNumber" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="注册地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入注册地址" />
        </el-form-item>
        <el-form-item label="注册电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入注册电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantInvoiceTemplateList,
  addMerchantInvoiceTemplate,
  updateMerchantInvoiceTemplate,
  deleteMerchantInvoiceTemplate,
  setDefaultMerchantInvoiceTemplate
} from '@/api/merchant'

// 模板列表数据
const loading = ref(false)
const templateList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: 'normal',
  title: '',
  taxNumber: '',
  bankName: '',
  bankAccount: '',
  address: '',
  phone: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入发票抬头', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  taxNumber: [
    { required: true, message: '请输入税号', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{15,20}$/, message: '请输入正确的税号', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入注册地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入注册电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ]
}

// 获取模板列表
const getTemplateList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantInvoiceTemplateList()
    templateList.value = data
  } catch (error) {
    console.error('获取发票模板列表失败:', error)
    ElMessage.error('获取发票模板列表失败')
  } finally {
    loading.value = false
  }
}

// 添加模板
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'type' ? 'normal' : ''
  })
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantInvoiceTemplate(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantInvoiceTemplate(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getTemplateList()
  } catch (error) {
    console.error('保存发票模板失败:', error)
  }
}

// 设置默认模板
const handleSetDefault = async (row) => {
  try {
    await ElMessageBox.confirm('确认将该模板设为默认模板吗？', '提示', {
      type: 'warning'
    })
    await setDefaultMerchantInvoiceTemplate(row.id)
    ElMessage.success('设置成功')
    getTemplateList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('设置默认模板失败:', error)
    }
  }
}

// 删除模板
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该模板吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantInvoiceTemplate(row.id)
    ElMessage.success('删除成功')
    getTemplateList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除发票模板失败:', error)
    }
  }
}

onMounted(() => {
  getTemplateList()
})
</script>

<style lang="scss" scoped>
.invoice-template {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .template-list {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 